/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xuexiang.xuidemo.slice.tabbar;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.PageSlider;
import ohos.agp.components.PageSliderProvider;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.Point;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.bundle.AbilityInfo;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import com.xuexiang.xui_lib.component.textview.badge.Badge;
import com.xuexiang.xui_lib.tabbar.VerticalTabLayout;
import com.xuexiang.xui_lib.tabbar.vertical.TabAdapter;
import com.xuexiang.xui_lib.tabbar.vertical.TabView;
import com.xuexiang.xuidemo.ResourceTable;
import com.xuexiang.xuidemo.slice.BaseAbilitySlice;
import com.xuexiang.xuidemo.util.DisplayUtils;
import com.xuexiang.xuidemo.util.XToastUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * 垂直的TabLayout
 *
 * @since 2021-04-16
 */
public class VerticalTabLayoutSlice extends BaseAbilitySlice {

    private static final int DEFAULT_HEIGHT = 25;
    private VerticalTabLayout tabLayout0;
    private VerticalTabLayout tabLayout1;
    private VerticalTabLayout tabLayout2;
    private VerticalTabLayout tabLayout;
    private PageSlider mViewPager;
    private Context context;

    @Override
    protected void initComponents() {
        initViews();

        // 默认横屏进入设置参数
        if (getDisplayWidthInPx() > getDisplayHeightInPx()) {
            tabLayout0.mTabHeight = DisplayUtils.vp2px(context, DEFAULT_HEIGHT);
            tabLayout0.setTabMode(VerticalTabLayout.TAB_MODE_SCROLLABLE);
        }
    }

    @Override
    protected int getUIContentLayoutId() {
        return ResourceTable.Layout_slice_vertical_tab;
    }

    @Override
    protected int getTitleBarId() {
        return ResourceTable.Id_title_bar;
    }

    @Override
    protected void onOrientationChanged(AbilityInfo.DisplayOrientation displayOrientation) {
        super.onOrientationChanged(displayOrientation);
        if (displayOrientation == AbilityInfo.DisplayOrientation.LANDSCAPE) {
            tabLayout0.mTabHeight = DisplayUtils.vp2px(context, DEFAULT_HEIGHT);
            tabLayout0.setTabMode(VerticalTabLayout.TAB_MODE_SCROLLABLE);
        } else {
            tabLayout0.mTabHeight = DirectionalLayout.LayoutConfig.MATCH_CONTENT;
            tabLayout0.setTabMode(VerticalTabLayout.TAB_MODE_FIXED);
        }
    }

    /**
     * 初始化控件
     */
    private void initViews() {
        context = this;
        tabLayout0 = (VerticalTabLayout) findComponentById(ResourceTable.Id_tab_layout0);
        tabLayout1 = (VerticalTabLayout) findComponentById(ResourceTable.Id_tab_layout1);
        tabLayout2 = (VerticalTabLayout) findComponentById(ResourceTable.Id_tab_layout2);
        tabLayout = (VerticalTabLayout) findComponentById(ResourceTable.Id_tab_layout);
        mViewPager = (PageSlider) findComponentById(ResourceTable.Id_viewpager);

        tabLayout0.onFinishInflate();
        tabLayout1.onFinishInflate();
        tabLayout2.onFinishInflate();
        tabLayout.onFinishInflate();
        mViewPager.setProvider(new MyPagerAdapter());

        initTab0();
        initTab1();
        initTab2();
        initTab3();
    }

    private void initTab0() {
        tabLayout0.setupWithViewPager(mViewPager);
        tabLayout0.setTabBadge(2, -1);
        tabLayout0.setTabBadge(3, -1);
        tabLayout0.setTabBadge(4, -1);
        tabLayout0.setTabBadge(7, 32);
        tabLayout0.addOnTabSelectedListener(new VerticalTabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabView tab, int position) {
                XToastUtils.toast("选中 " + tab.getTitle().getContent());
            }

            @Override
            public void onTabUnselected(final TabView tab, int position) {
                EventRunner mainEventRunner = EventRunner.getMainEventRunner();
                EventHandler eventHandler = new EventHandler(mainEventRunner);
                eventHandler.postTask(() -> XToastUtils.toast("选择取消 " + tab.getTitle().getContent()), 500);
            }

            @Override
            public void onTabReselected(TabView tab, int position) {
                XToastUtils.toast("重复选择 " + tab.getTitle().getContent());
            }
        });
    }

    private void initTab1() {
        tabLayout1.setupWithViewPager(mViewPager);
    }

    private void initTab2() {
        tabLayout2.setupWithViewPager(mViewPager);
        tabLayout2.setTabBadge(2, -1);
        tabLayout2.setTabBadge(8, -1);
        tabLayout2.getTabAt(3)
            .setBadge(new TabView.TabBadge.Builder().setBadgeGravity(LayoutAlignment.START
                | LayoutAlignment.TOP)
                .setBadgeNumber(999)
                .setOnDragStateChangedListener((dragState, badge, targetView) -> {
                    if (dragState == Badge.OnDragStateChangedListener.STATE_SUCCEED) {
                        badge.setBadgeNumber(-1).stroke(new Color(0xFFFFFFFF), 1);
                    }
                }).build());
    }

    private void initTab3() {
        tabLayout.setTabAdapter(new MyTabAdapter());
    }

    private class MyTabAdapter implements TabAdapter {
        List<MenuBean> menus;

        public MyTabAdapter() {
            menus = new ArrayList<>();
            Collections.addAll(menus,
                new MenuBean(ResourceTable.Media_menu_01_pressed, ResourceTable.Media_menu_01_none, "汇总"),
                new MenuBean(ResourceTable.Media_menu_02_pressed, ResourceTable.Media_menu_02_none, "图表"),
                new MenuBean(ResourceTable.Media_menu_03_pressed, ResourceTable.Media_menu_03_none, "收藏"),
                new MenuBean(ResourceTable.Media_menu_04_pressed, ResourceTable.Media_menu_04_none, "竞拍"));
        }

        @Override
        public int getCount() {
            return menus.size();
        }

        @Override
        public TabView.TabBadge getBadge(int position) {
            return new TabView.TabBadge.Builder().setBadgeNumber(999).setBackgroundColor(0xff2faae5)
                .setOnDragStateChangedListener((dragState, badge, targetView) -> {
                }).build();
        }

        @Override
        public TabView.TabIcon getIcon(int position) {
            MenuBean menu = menus.get(position);
            return new TabView.TabIcon.Builder()
                .setIcon(menu.mSelectIcon, menu.mNormalIcon)
                .setIconGravity(LayoutAlignment.START)
                .setIconMargin(DisplayUtils.vp2px(context, 5))
                .setIconSize(DisplayUtils.vp2px(context, 20), DisplayUtils.vp2px(context, 20))
                .build();
        }

        @Override
        public TabView.TabTitle getTitle(int position) {
            MenuBean menu = menus.get(position);
            return new TabView.TabTitle.Builder(context)
                .setContent(menu.mTitle)
                .setTextColor(0xFF36BC9B, 0xFF757575)
                .build();
        }

        @Override
        public int getBackground(int position) {
            return -1;
        }
    }

    private class MyPagerAdapter extends PageSliderProvider implements TabAdapter {
        List<String> titles;

        public MyPagerAdapter() {
            titles = new ArrayList<>();
            Collections.addAll(titles, "ohos", "IOS", "Web", "JAVA", "C++",
                ".NET", "JavaScript", "Swift", "PHP", "Python", "C#", "Groovy", "SQL", "Ruby");
        }

        @Override
        public int getCount() {
            return titles.size();
        }

        @Override
        public TabView.TabBadge getBadge(int position) {
            if (position == 5) {
                return new TabView.TabBadge.Builder().setBadgeNumber(666)
                    .setExactMode(true)
                    .setOnDragStateChangedListener((dragState, badge, targetView) -> {
                    }).build();
            }
            return null;
        }

        @Override
        public TabView.TabIcon getIcon(int position) {
            return null;
        }

        @Override
        public TabView.TabTitle getTitle(int position) {
            return new TabView.TabTitle.Builder(context)
                .setContent(titles.get(position))
                .setTextColor(Color.WHITE.getValue(), 0xBBFFFFFF)
                .build();
        }

        @Override
        public int getBackground(int position) {
            return 0;
        }

        @Override
        public Object createPageInContainer(ComponentContainer container, int position) {
            Text textView = new Text(context);
            ComponentContainer.LayoutConfig layoutConfig = new ComponentContainer.LayoutConfig();
            layoutConfig.width = ComponentContainer.LayoutConfig.MATCH_PARENT;
            layoutConfig.height = ComponentContainer.LayoutConfig.MATCH_PARENT;
            textView.setLayoutConfig(layoutConfig);
            textView.setTextAlignment(TextAlignment.CENTER);
            textView.setTextColor(Color.GRAY);
            textView.setTextSize(DisplayUtils.vp2px(context, 16));
            textView.setText(String.format("这个是%s页面的内容", titles.get(position)));
            container.addComponent(textView);
            return textView;
        }

        @Override
        public void destroyPageFromContainer(ComponentContainer container, int position, Object object) {
            container.removeComponent((Component) object);
        }

        @Override
        public boolean isPageMatchToObject(Component component, Object object) {
            return component == object;
        }
    }

    static class MenuBean {
        public int mSelectIcon;
        public int mNormalIcon;
        public String mTitle;

        public MenuBean(int mSelectIcon, int mNormalIcon, String mTitle) {
            this.mSelectIcon = mSelectIcon;
            this.mNormalIcon = mNormalIcon;
            this.mTitle = mTitle;
        }
    }

    /**
     * 获取屏幕宽度
     *
     * @return 屏幕宽度
     */
    public int getDisplayWidthInPx() {
        return (int) getDisplayPoint().orElse(new Point()).getPointX();
    }

    /**
     * 获取屏幕高度，不包含状态栏的高度
     *
     * @return 屏幕高度，不包含状态栏的高度
     */
    public int getDisplayHeightInPx() {
        return (int) getDisplayPoint().orElse(new Point()).getPointY();
    }

    /**
     * 获取屏幕的Point, 可获取屏幕宽高属性
     *
     * @return 可获取屏幕宽高属性Point
     */
    public Optional<Point> getDisplayPoint() {
        return DisplayManager.getInstance().getDefaultDisplay(this)
            .map(display -> {
                Point point = new Point();
                display.getSize(point);
                return Optional.of(point);
            }).orElse(null);
    }
}
